#include <iostream>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <cstring>
#include <cstdlib>

// 自制malloc
void* my_malloc(size_t size)
{
    if(size > 0)
    {
        void* ptr = mmap(nullptr , size , PROT_WRITE | PROT_READ , MAP_PRIVATE | MAP_ANONYMOUS , -1 , 0);
        if(ptr == MAP_FAILED)
        {
            return nullptr;
        }
        return ptr;
    }
    return nullptr;
}

void my_free(void* ptr , size_t size)
{
    if(ptr!= nullptr && size > 0)
    {
        if(munmap(ptr , size) < 0)
        {
            std::cerr << "munmap error" << std::endl;
        }
    }
}


int main()
{
    void* p = my_malloc(1024);
    char* pch = static_cast<char*>(p);
    for(int i = 0 ; i < 26 ; i++)
        pch[i] = 'a' + i;

    for(int i = 0 ; i < 26 ; i++)
        std::cout << pch[i];

    my_free(p , 1024);
    return 0;
}





int test1() 
{
    // 先打开一个文件
    int fd = open("./log.txt" , O_CREAT | O_RDWR | O_TRUNC , 0666);
    if(fd < 0)
    {
        std::cerr << "open file error , in file :"  << __FILE__ << " line : " << __LINE__ << std::endl;;
        exit(1);
    }

    // 修改文件大小
    if(ftruncate(fd , 1024) < 0)
    {
        std::cerr << "ftruncate error , in file :"  << __FILE__ << " line : " << __LINE__ << std::endl;
        exit(5);
    }


    // 进行文件映射
    void* p = mmap(nullptr , 1024 , PROT_WRITE | PROT_READ , MAP_SHARED , fd , 0);
    if(p == MAP_FAILED)
    {
        std::cerr << "mmap error , in file :"  << __FILE__ << " line : " << __LINE__ << std::endl;
        exit(2);
    }

    // 写入数据
    char* pch = static_cast<char*>(p);

    for(int i = 0 ; i < 26 ; i++)
        pch[i] = 'a' + i;

    // 关闭映射 ， 并关闭文件
    if(munmap(p , 1024) < 0)
    {
        std::cerr << "munmap error , in file :"  << __FILE__ << " line : " << __LINE__ << std::endl;
        exit(3);
    }

    close(fd);
    return 0;
}
